package com.example.smssender.contactimport.impl;

import android.content.Context;
import android.net.Uri;
import com.example.smssender.Contact;
import com.example.smssender.contactimport.ContactImporter;
import com.example.smssender.contactimport.ContactImportManager;
import com.example.smssender.contactimport.ImportResult;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * JSON 文件导入器
 */
public class JsonContactImporter implements ContactImporter {
    
    @Override
    public ImportResult importContacts(Context context, Uri source) {
        ImportResult result = new ImportResult();
        
        if (source == null) {
            result.setSuccess(false);
            result.addError("文件URI为空");
            return result;
        }
        
        try {
            InputStream inputStream = context.getContentResolver().openInputStream(source);
            if (inputStream == null) {
                result.setSuccess(false);
                result.addError("无法打开文件");
                return result;
            }
            
            List<Contact> contacts = parseJsonFile(inputStream);
            inputStream.close();
            
            // 验证和统计
            List<Contact> validContacts = new ArrayList<>();
            for (Contact contact : contacts) {
                if (ContactImportManager.validateContact(contact)) {
                    validContacts.add(contact);
                } else {
                    result.addError("无效数据：" + (contact.getName() != null ? contact.getName() : "未知"));
                }
            }
            
            result.setTotalCount(contacts.size());
            result.setSuccessCount(validContacts.size());
            result.setFailCount(contacts.size() - validContacts.size());
            result.setContacts(validContacts);
            result.setSuccess(true);
            
        } catch (Exception e) {
            result.setSuccess(false);
            result.addError("解析JSON文件失败：" + e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 解析JSON文件
     */
    private List<Contact> parseJsonFile(InputStream inputStream) throws Exception {
        List<Contact> contacts = new ArrayList<>();
        
        InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
        JsonElement jsonElement = JsonParser.parseReader(reader);
        reader.close();
        
        if (!jsonElement.isJsonArray()) {
            throw new Exception("JSON格式错误：根元素必须是数组");
        }
        
        JsonArray jsonArray = jsonElement.getAsJsonArray();
        
        for (JsonElement element : jsonArray) {
            if (!element.isJsonObject()) {
                continue;
            }
            
            JsonObject obj = element.getAsJsonObject();
            
            // 尝试多种字段名
            String name = getStringValue(obj, "name", "姓名", "Name", "displayName");
            String phone = getStringValue(obj, "phoneNumber", "phone", "手机号", "手机", "电话", "mobile", "PhoneNumber");
            
            if (name != null && !name.trim().isEmpty() && phone != null && !phone.trim().isEmpty()) {
                // 清理手机号
                phone = ContactImportManager.normalizePhoneNumber(phone);
                Contact contact = new Contact(name.trim(), phone);
                contacts.add(contact);
            }
        }
        
        return contacts;
    }
    
    /**
     * 从JSON对象中获取字符串值（尝试多个键名）
     */
    private String getStringValue(JsonObject obj, String... keys) {
        for (String key : keys) {
            if (obj.has(key) && obj.get(key).isJsonPrimitive()) {
                String value = obj.get(key).getAsString();
                if (value != null && !value.trim().isEmpty()) {
                    return value;
                }
            }
        }
        return null;
    }
    
    @Override
    public String getName() {
        return "JSON文件导入";
    }
    
    @Override
    public String getDescription() {
        return "从JSON文件导入联系人";
    }
}

